import sys, os, sqlite3, logging, socket
import cherrypy
from cherrypy.lib.static import serve_file
import mimetypes

from avahi_service import AvahiService

def server(env):
    """
    Runs a cherrypy http server for files you want to share.
    """
    def formatter(pathlist):
        ret = ''
        for p in pathlist:
            ret += '<li><a href="%s">%s</a></li>' % (p,p)
        return ret

    class FileServer(object):
        def index(self):
            # connections are dubiously threadsafe
            conn = sqlite3.connect( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME')) )
            cursor = conn.cursor()
            paths = [x[0] for x in cursor.execute(env.get('SELECT_ALL_PATHS')).fetchall()]

            # FIXME: This whole thing seems like bad practice:
            template = file(os.path.join('templates', 'homepage.html'),'r').read() 
            
            return template % ( formatter(paths) )

        def default(self,*path):
            prelim = os.path.join(path[0], *path[1:]) # evil syntax
            if sys.platform == 'win32':
                prelim = 'C:\\' + prelim
            else:
                prelim = '/' + prelim
            conn = sqlite3.connect( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME')) )
            cursor = conn.cursor()

            if cursor.execute('SELECT path FROM ffshare_files WHERE path == ?;', (prelim,)).fetchall(): # FIXME
                if os.path.exists(prelim) and os.access(prelim, os.R_OK) and not os.path.isdir(prelim):
                    mime = mimetypes.guess_type(prelim)
                    if mime[0]:
                        return serve_file(prelim, mime[0], "attachment")
                    else:
                        return serve_file(prelim, "application/x-download", "attachment")
                else:
                    logging.error('invalid file or didn\'t have access')
            else:
                logging.error('cursor not found')

            cherrypy.response.status = 404
            return self.index()

        default.exposed = True
        index.exposed = True

    cherrypy.config['server.socket_port'] = env.get('PORT')
    avs = AvahiService('FFShare-%s' % socket.gethostname(), '_fhttp._tcp', env.get('PORT'))
    avs.start()
    cherrypy.quickstart(FileServer())
